import store from '../../utils/store'
import * as types from '../mutation-types'
import _ from 'lodash'
const app = {
  state: {
    sidebar: {
      opened: !+store.get('sidebarStatus')
    },
    theme: 'default',
    livenewsChannels: store.get('livenewsChannels') || '[]',
    visitedViews: []
  },
  getters: {
    sidebar: state => state.sidebar,
    visitedViews: state => state.visitedViews
  },
  mutations: {
    [types.TOGGLE_SIDEBAR] (state) {
      if (state.sidebar.opened) {
        store.set('sidebarStatus', 1)
      } else {
        store.set('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
    },
    [types.ADD_VISITED_VIEWS] (state, view) {
      if (state.visitedViews.some(v => v.name === view.meta.name_str)) {
        const thisView = _.find(state.visitedViews, v => {
          return v.name === view.meta.name_str
        })
        thisView.path = view.path
      } else {
        state.visitedViews.push({ name: view.meta.name_str, path: view.path })
      }
    },
    [types.DEL_VISITED_VIEWS] (state, view) {
      let index
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.path === view.path) {
          index = i
          break
        }
      }
      state.visitedViews.splice(index, 1)
    },
    [types.CLEAR_VISITVIEW] (state) {
      state.visitedViews = []
    }
  },
  actions: {
    ToggleSideBar: ({ commit }) => {
      commit(types.TOGGLE_SIDEBAR)
    },
    addVisitedViews: ({ commit }, view) => {
      commit(types.ADD_VISITED_VIEWS, view)
    },
    delVisitedViews: ({ commit }, view) => {
      commit(types.DEL_VISITED_VIEWS, view)
    }
  }
}

export default app
